<template>
  <div class="flowNodeSort">
    <el-table :data="list" border row-key="id" align="left">
      <el-table-column
        v-for="(item, index) in col"
        :key="`col_${index}`"
        :prop="col[index].prop"
        :label="item.label"
      >
      </el-table-column>
    </el-table>
    <br />
    <el-row>
      <el-col :span="3" :offset="9"
        ><el-button type="primary" @click="saveSort()"
          >提交修改</el-button
        ></el-col
      >
    </el-row>
  </div>
</template>

<script>
import Sortable from "sortablejs";
import qs from "qs";

export default {
  name: "FlowNodeSort",
  props: ["fFlowId", "fList"],
  data() {
    return {
      col: [
        {
          label: "序号",
          prop: "sort"
        },
        {
          label: "节点名",
          prop: "name"
        }
      ],
      list: [],
      flowId: null
    };
  },
  watch: {
    fList(val) {
      this.list = JSON.parse(JSON.stringify(this.fList));
    }
  },
  created() {
    this.flowId = this.fFlowId;
    this.list = JSON.parse(JSON.stringify(this.fList));
  },
  mounted() {
    this.rowDrop();
  },
  methods: {
    //行拖拽
    rowDrop() {
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          console.log("newIndex:" + newIndex + "  oldIndex:" + oldIndex);
          const currRow = _this.list.splice(oldIndex, 1)[0];
          _this.list.splice(newIndex, 0, currRow);
          //修改节点的sort
          for (let i = 0; i < _this.list.length; ) {
            _this.list[i].sort = ++i;
          }
        }
      });
    },
    saveSort() {
      const ids = new Array();
      this.list.forEach(e => {
        ids.push(e.id);
      });
      var that = this;
      this.$axios
        .get("node/sort", {
          params: { 'ids': ids, flowId: this.flowId},
          paramsSerializer: params => {
            return qs.stringify(params, { indices: false });
          }
        })
        .then(res => {
          let data = res.data;
          if (data.code === 0) {
            this.$message({ message: data.msg, type: 'success'});
            this.$emit('input',false);
            this.$emit('flush-data');
          } else {
            alert(data.msg);
          }
        })
        .catch(function(error) {
          console.log("axios请求异常:" + error);
          that.$message.error("网路请求异常");
        });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>
